<template>
  <div class="tem-table">
    <CHeader :keyword="keyword" @onKeywordChange="onKeywordChange" @onClearKeyword="onClearKeyword" @onSearch="onSearch"
             @onReset="onReset"
             @onNew="onNew"/>
    <div class="tem-table-box">
      <el-table v-loading="loading" height="100%" :data="tableData" border style="width: 100%">
        <el-table-column prop="id" label="用户ID" min-width="100"/>
        <el-table-column prop="uname" label="用户名" min-width="100"/>
        <el-table-column prop="name" label="姓名" min-width="80"/>
        <el-table-column prop="sexName" label="性别" min-width="80"/>
        <el-table-column prop="jobTitle" label="职称" min-width="100"/>
        <el-table-column prop="mobile" label="手机号" min-width="110"/>
        <el-table-column prop="email" label="邮箱" min-width="140"/>
        <el-table-column label="角色" min-width="100">
          <template #default="{ row }">
            <el-tag v-for="item in row.roleName.split(',')" type="success" style="margin: 4px">
              {{ item }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column label="操作" min-width="260">
          <template #default="{ row }">
            <el-button link type="primary" size="small" @click="onNew(row)">编辑</el-button>
            <el-button link type="danger" size="small" @click="onDel(row.id)">删除</el-button>
            <el-button link type="success" size="small" @click="onExportUrl(row.id)">导出外部链接</el-button>
            <el-button link type="success" size="small" @click="onCreatePerpetualToken(row.id)">获取永久Token</el-button>
          </template>
        </el-table-column>
      </el-table>
    </div>
    <div style="display: flex; justify-content: flex-end; padding: 10px;">
      <el-pagination
          v-model:current-page="pageNo"
          v-model:page-size="pageSize"
          :page-sizes="[10, 20, 30, 50]"
          layout="total, sizes, prev, pager, next, jumper"
          :total="total"
          background
          @size-change="handleSizeChange"
          @current-change="handleNoChange"
      />
    </div>
  </div>

  <el-dialog v-model="showExportUrlModal" title="导出外部地址" width="400px">
    <el-form :rules="exportOpenUrlRules" ref="exportOpenUrlFormRef" :model="exportOpenUrlForm" label-width="100px">
      <el-form-item label="根页面路径" prop="pagePath">
        <el-input placeholder="请输入根页面路径，比如：user/details" style="width: 100%"
                  v-model="exportOpenUrlForm.pagePath"></el-input>
      </el-form-item>
      <el-form-item label="认证秘钥" prop="authKey">
        <el-input placeholder="请输入认证秘钥，并妥善保管" style="width: 100%"
                  v-model="exportOpenUrlForm.authKey"></el-input>
      </el-form-item>
    </el-form>
    <template #footer>
      <el-button @click="showExportUrlModal = false">取 消</el-button>
      <el-button type="primary" @click="exportOpenUrl(exportOpenUrlFormRef)">导 出</el-button>
    </template>
  </el-dialog>


  <el-dialog v-model="showImportUser" :title="isEdit?'编辑成员':'新增成员'" width="400px"
             :before-close="closeImportUser">
    <el-form label-width="100px" ref="formRef" :model="form" :rules="rules">
      <el-form-item label="选择用户" prop="uid" v-show="!isEdit">
        <el-select multiple filterable v-model="form.uid" placeholder="请选择用户">
          <el-option v-for="item in userList" :label="item.name" :value="item.id"></el-option>
        </el-select>
      </el-form-item>
      <el-form-item label="用户角色" prop="groupRoleId">
        <el-select
            filterable
            v-model="form.roleIds"
            placeholder="请选择角色"
            multiple
        >
          <el-option v-for="item in roleList" :label="item.roleName" :value="item.id"></el-option>
        </el-select>
      </el-form-item>
    </el-form>
    <div class="divider"/>
    <template #footer>
      <el-button type="primary" @click="importUser(formRef)">确定</el-button>
    </template>

  </el-dialog>
</template>

<script setup lang="ts">
import {onBeforeMount} from 'vue';
import type {FormInstance} from 'element-plus';
import {
  ElMessage,
  ElMessageBox,
} from 'element-plus';

import CHeader from '@/components/CHeader.vue';
import {
  adminGetAppUserList,
  delAppUser,
  editAppUser, EditAppUserArgs, getAppOpenUrl, getAppRoleList, getUserSelectedRoleIds,
} from '@/service/AppManager';
import type {UserMo} from "@/service/entity/UserMo";
import type {AppRoleMo} from "@/service/entity/AppRoleMo";
import {createPerpetualToken, getAllUserList} from "@/service/UserManager";

const props = defineProps<{
  appId: any
}>()

onBeforeMount(async () => {
  await updata()
  const res = await getAppRoleList({
    all: true,
    appId: props.appId
  })
  if (res) {
    roleList.value = res.arr
  }

  const data = await getAllUserList({all: true})
  if (data) {
    userList.value = data.arr
  }
})
const formRef = ref<FormInstance>()
const total = ref(0)
const pageNo = ref(1)
const pageSize = ref(10)
const keyword = ref('')
const tableData = ref<any>([])
const loading = ref(false)
const isEdit = ref(false)
const showExportUrlModal = ref(false)


const exportOpenUrlForm = reactive({
  uid: 0,
  pagePath: '',
  authKey: ''
})
const exportOpenUrlFormRef = ref<FormInstance>()
const exportOpenUrlRules = reactive({
  pagePath: {required: true, message: '页面根路径不可为空', trigger: 'blur'},
  authKey: {required: true, message: '认证秘钥不可为空', trigger: 'blur'},
})

const form = reactive<EditAppUserArgs>({
  appId: '',
  roleIds: [],
  uid: []
})
const rules = reactive({
  roleId: [
    {required: true, message: '角色必选', trigger: 'blur'},
  ],
  uid: [{
    required: true, message: '用户必填', trigger: 'blur'
  }]
})
let roleList = ref<AppRoleMo[]>([])
let userList = ref<UserMo[]>([])
const onKeywordChange = (val: string) => {
  keyword.value = val
  updata()
}

const onClearKeyword = () => {
  keyword.value = ''
  updata()
}

const onSearch = async () => {
  updata()
}

const onReset = async () => {
  keyword.value = ''
  pageNo.value = 1
  pageSize.value = 10
  updata()
}

const onNew = async (row?: UserMo) => {
  if (row) {
    const res = await getUserSelectedRoleIds(props.appId, row.id)
    if (res) {
      form.roleIds = res.arr
    }
    form.appId = props.appId
    form.uid = [row.id]
    isEdit.value = true
  } else {
    for (let key in form) {
      form[key] = ''
    }
    form.appId = props.appId
    isEdit.value = false
  }
  showImportUser.value = true
}

const onDel = (id: string) => {
  ElMessageBox.confirm(
      '永久删除该条信息. 是否确认?',
      'Warning',
      {
        confirmButtonText: '确认',
        cancelButtonText: '取消',
        type: 'warning',
      }
  )
      .then(async () => {
        const res = await delAppUser(props.appId, id)
        if (res) {
          updata()
        }
      })
      .catch(() => {
        ElMessage({
          type: 'info',
          message: '取消删除',
        })
      })

}

async function onCreatePerpetualToken(uid: any) {
  const res = await createPerpetualToken(uid, props.appId)
  if (!res) {
    ElMessage({
      type: 'error',
      message: '获取永久Token失败'
    })
    return
  }
  await navigator.clipboard.writeText(res)
  ElMessage({
    type: 'success',
    message: 'Token已复制到粘贴板'
  })
}

const onExportUrl = (uid: any) => {
  exportOpenUrlForm.uid = uid
  showExportUrlModal.value = true
}

async function exportOpenUrl(formRef: FormInstance | undefined) {
  if (!formRef) {
    return
  }
  await formRef.validate(async (valid, fields) => {
    if (valid) {
      const res = await getAppOpenUrl(props.appId, exportOpenUrlForm.uid, exportOpenUrlForm.pagePath, exportOpenUrlForm.authKey)
      if (!res) return false
      await navigator.clipboard.writeText(res.data)
      ElMessage({
        type: 'success',
        message: '已复制到粘贴板'
      })
      showExportUrlModal.value = false
      exportOpenUrlFormRef.resetFields()
      return true
    } else {
      return false
    }
  })


}

async function updata() {
  loading.value = true
  try {
    const res = await adminGetAppUserList({
      appId: props.appId,
      pageNo: pageNo.value,
      pageSize: pageSize.value,
      keyword: keyword.value
    })
    tableData.value = res.arr
    total.value = res.total
  } finally {
    setTimeout(() => loading.value = false, 200)
  }
}

const handleSizeChange = (val: number) => {
  pageSize.value = val
  updata()
}
const handleNoChange = (val: number) => {
  pageNo.value = val
  updata()
}

const showImportUser = ref(false)

const importUser = async (formRef: FormInstance | undefined) => {
  if (!formRef) {
    return
  }
  await formRef.validate(async (valid, fields) => {
    if (valid) {
      for (let uid of form.uid) {
        const res = await editAppUser({
          appId: form.appId,
          roleIds: form.roleIds,
          uid: uid
        })
        if (!res) return false
      }
      formRef.resetFields()
      showImportUser.value = false
      updata()
      ElMessage({
        type: 'success',
        message: '已提交'
      })
      return true
    } else {
      return false
    }
  })
}

function closeImportUser() {
  showImportUser.value = false
  form.resetFields()
}

</script>

<style scoped lang="scss">
@import "@/global.scss";

.tem-table {
  height: 100%;
  display: flex;
  flex-direction: column;
  box-sizing: border-box;
  padding: 10px;
}


.tem-table-box {
  flex: 1;
  overflow: hidden;
}

.import-user-modal {
  .divider {
    height: 15px;
  }

  .label {
    display: flex;
    justify-content: flex-end;
    width: 55px;
  }
}
</style>